package org.tio.showcase.websocket.server;

import java.util.Objects;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.internal.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.Tio;
import org.tio.core.ChannelContext;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.showcase.UserServer;
import org.tio.utils.json.Json;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.common.WsSessionContext;
import org.tio.websocket.server.handler.IWsMsgHandler;

/**
 * @author tanyaowu
 * 2017年6月28日 下午5:32:38
 */
public class ShowcaseWsMsgHandler implements IWsMsgHandler {
	private static Logger log = LoggerFactory.getLogger(ShowcaseWsMsgHandler.class);

	public static final ShowcaseWsMsgHandler me = new ShowcaseWsMsgHandler();

	private ShowcaseWsMsgHandler() {

	}


//	private UserServer userServer;

	/**
	 * 握手时走这个方法，业务可以在这里获取cookie，request参数等
	 */
	@Override
	public HttpResponse handshake(HttpRequest request, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
		String clientip = request.getClientIp();
		String myname = request.getParam("name");
        String token = request.getParam("token");
        UserServer userServer = new UserServer();


//
//		除了可以绑定userid，t-io还内置了如下绑定API
//
//		绑定业务id
//		Tio.bindBsId(ChannelContext channelContext, String bsId)

//		绑定token
//		Tio.bindToken(ChannelContext channelContext, String token)

//		绑定群组
//		Tio.bindGroup(ChannelContext channelContext, String group)

        if (StrUtil.isNotEmpty(token)) {
            System.out.println("token = " + token);
//			System.out.println("userServer.tokenGetUserIdByString(token) = " + userServer.tokenGetUserIdByString(token));
            Tio.bindUser(channelContext, userServer.tokenGetUserIdByString(token));
            Tio.bindToken(channelContext, token);//		绑定token
            channelContext.setUserid(userServer.tokenGetUserIdByString(token));
        } else {
            Tio.bindUser(channelContext, myname);
            channelContext.setUserid(myname);
//			channelContext.setUserid(userServer.tokenGetUserIdByString(token));
        }


        log.info("收到来自{}的ws握手包\r\n{}", "clientip:" + clientip, request.toString());
		return httpResponse;
	}

	/** 
	 * @param httpRequest
	 * @param httpResponse
	 * @param channelContext
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
		//绑定到群组，后面会有群发
		Tio.bindGroup(channelContext, Const.GROUP_ID);
		
		int count = Tio.getAll(channelContext.tioConfig).getObj().size();

		String msg = "{name:'admin',message:'" + channelContext.userid + " 进来了，共【" + count + "】人在线" + "'}";
		//用tio-websocket，服务器发送到客户端的Packet都是WsResponse
		System.out.println("msg = " + msg);
		WsResponse wsResponse = WsResponse.fromText(msg, ShowcaseServerConfig.CHARSET);//utf-8
		//群发
		
		Tio.sendToGroup(channelContext.tioConfig, Const.GROUP_ID, wsResponse);
	}

	/**
	 * 字节消息（binaryType = arraybuffer）过来后会走这个方法
	 */
	@Override
	public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
		return null;
	}

	/**
	 * 当客户端发close flag时，会走这个方法
	 */
	@Override
	public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
		Tio.remove(channelContext, "receive close flag");
		return null;
	}

	/*
	 * 字符消息（binaryType = blob）过来后会走这个方法
	 */
	@Override
	public Object onText(WsRequest wsRequest, String text, ChannelContext channelContext) throws Exception {
		WsSessionContext wsSessionContext = (WsSessionContext) channelContext.get();
		HttpRequest httpRequest = wsSessionContext.getHandshakeRequest();//获取websocket握手包
		if (log.isDebugEnabled()) {
			log.debug("握手包:{}", httpRequest);
		}

        String groupName = Const.GROUP_ID;
        String msg = "";


		JSONObject obj = JSONObject.parseObject(text);
		String action = obj.getString("action");
        String user_msg = obj.getString("msg");
		switch (action){
			case "ping":
				return null;

			case "chat":

				System.out.println("2人聊");
                groupName = "id" + "id";

                msg = "{name:'" + channelContext.userid + "',message:'" + user_msg + ",send_user_id:" + channelContext.userid + "'}";
                //绑定到群组（正常有个加群的消息请求）
                Tio.bindGroup(channelContext, groupName);
				break;

			case "group":

				System.out.println("群聊");

                groupName = "group." + obj.getString("group");

                msg = "{name:'" + channelContext.userid + "',message:'" + text + "'}";

                //绑定到群组（正常有个加群的消息请求）
                Tio.bindGroup(channelContext, groupName);
				break;

			case "isupdate":
				groupName = obj.getString("group");
				Tio.bindGroup(channelContext, groupName);
				System.out.println("isupdate = " + text);
				System.out.println("groupName = " + groupName);
				break;


			default:
                log.info("收到ws未知消息:{}", text);

		}



		if (Objects.equals("心跳内容", text)) {
			return null;
		}
		//channelContext.getToken()
		//String msg = channelContext.getClientNode().toString() + " 说：" + text;

		//用tio-websocket，服务器发送到客户端的Packet都是WsResponse
		WsResponse wsResponse = WsResponse.fromText(msg, ShowcaseServerConfig.CHARSET);
		//群发
        Tio.sendToGroup(channelContext.tioConfig, groupName, wsResponse);

		//返回值是要发送给客户端的内容，一般都是返回null
		return null;
	}

}
